<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.name" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getListData">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="listData" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection">
			</el-table-column>
			<el-table-column type="index" fixed>
			</el-table-column>
			<el-table-column prop="username" label="用户名" fixed sortable>
			</el-table-column>
			<el-table-column prop="tel" label="电话" sortable>
			</el-table-column>
			<el-table-column prop="email" label="邮箱" sortable>
			</el-table-column>
			<el-table-column prop="role" label="角色" :formatter="formatRole" sortable>
			</el-table-column>
			<el-table-column prop="inputTime" label="输入时间" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" :formatter="formatState" sortable>
			</el-table-column>
			<el-table-column prop="unionId" label="第三方认证"  sortable>
			</el-table-column>
			<el-table-column prop="tenant.companyName" label="所属租户"  sortable>
			</el-table-column>


			<el-table-column label="操作" fixed="right" header-align="center" width="220">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
					<el-button type="warning" size="small" @click="handleRole(scope.$index, scope.row)">分配角色</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="editForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input placeholder="请输入密码" v-model="editForm.password" show-password></el-input>
				</el-form-item>
				<el-form-item label="电话" prop="tel">
					<el-input v-model="editForm.tel" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="editForm.email" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item :formatter="formatState" label="状态">
					<el-select v-model="editForm.state" :formatter="formatState" placeholder="请选择状态">
						<el-option label="离职" value="1"></el-option>
						<el-option label="正常" value="0"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="addForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="addForm.password" show-password auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="电话" prop="tel">
					<el-input v-model="addForm.tel" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="addForm.email" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-select v-model="addForm.state" placeholder="请选择状态">
						<el-option label="离职" value="1"></el-option>
						<el-option label="正常" value="0"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--分配角色-->
		<el-dialog title="分配角色" :visible.sync="RoleVisible" width="50%">
			<div>
				<p>当前用户:{{userInfo.username}}</p>
				<p>分配角色:
					<el-select v-model="selectRoleId" placeholder="请选择">
						<el-option
								v-for="item in roleList"
								:key="item.id"
								:label="item.name"
								:value="item.id">
						</el-option>
					</el-select>
				</p>
			</div>
			<span slot="footer" class="dialog-footer">
    			<el-button @click="RoleVisible = false">取 消</el-button>
    			<el-button type="primary" @click="saveRoleInfo">确 定</el-button>
 			 </span>
		</el-dialog>

	</section>
</template>

<script>
    import util from '../../../common/js/util'
    //import NProgress from 'nprogress'
    //import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

    export default {
        data() {
            return {
                filters: {
                    name: ''
                },
                listData: [],
                total: 0,
                keyword:'',
                pageSize: 10,
                currentPage:1,
                listLoading: false,
                sels: [],//列表选中列
                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                editFormRules: {
					username: [
						{ required: true, message: '请输入用户名', trigger: 'blur' }
					],
					password: [
						{ required: true, message: '请输入密码', trigger: 'blur' }
					],
					tel: [
						{ required: true, message: '请输入电话', trigger: 'blur' }
					],
					email: [
						{ required: true, message: '请输入邮箱', trigger: 'blur' }
					],
                },
                //编辑界面数据
                editForm: {
                    id: 0,
                    username: '',
                    password:'',
					tel:'',
					email:'',
					state:0,
                },

                addFormVisible: false,//新增界面是否显示
                addLoading: false,
                addFormRules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' }
                    ],
					tel: [
						{ required: true, message: '请输入电话', trigger: 'blur' }
					],
					email: [
						{ required: true, type:'email', message: '请输入邮箱', trigger: 'blur' }
					],
                },
                //新增界面数据
                addForm: {
					id: 0,
					username: '',
					password:'',
					tel:'',
					email:'',
					state:0,
                },
				//控制分配角色对话框
                RoleVisible:false,
				//需要被分配角色的用户信息
				userInfo:{},
				//所有角色的数据列表
				roleList:[],
				//以选中的角色id值
                selectRoleId:''

            }
        },
        methods: {

            //性别显示转换
            formatState: function (row, column) {
                return row.state == 1 ? '离职' : row.state == 0 ? '正常' : '未知';
            },
			//角色格式化
            formatRole(row,colim){
                if(row.role==null){
                    return '无角色';
				}
                return row.role.name;
			},

            handleCurrentChange(val) {
                this.currentPage=val;
                this.getListData();
            },
            //获取用户列表
            getListData() {
                let para = {
                    currentPage: this.currentPage,
                    pageSize:this.pageSize,
                    keyword: this.filters.name
                };
                this.listLoading = true;
                this.$http.post('/employee/findByPage',para).then(res=>{
                    let ajaxResult =  res.data
                    if (ajaxResult.success){
                        this.listData = ajaxResult.data.result;
                        this.total = ajaxResult.data.total
                    }else {
                        this.$message({
                            message: '加载失败',
                            type: 'error'
                        });
                    }
                    this.listLoading = false;
                }).catch(error=>{
                    this.listLoading = false;
                    this.$message({
                        message: '加载失败',
                        type: 'error'
                    });
                })
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.delete('/employee/delete/'+row.id,{}).then(res=>{
                        let ajaxResult =  res.data
                        if (ajaxResult.success){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getListData();
                        }else {
                            this.$message({
                                message: '删除失败',
                                type: 'error'
                            });
                        }
                        this.listLoading = false;
                    }).catch(error=>{
                        this.listLoading = false;
                        this.$message({
                            message: '删除失败',
                            type: 'error'
                        });
                    })

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
				this.$http.get('/employee/findById/'+row.id,{}).then(res=>{
					let ajaxResult = res.data
					console.log(res);
					if (ajaxResult.success){
						this.editForm.id = ajaxResult.data.id;
						this.editForm.username = ajaxResult.data.username;
						this.editForm.password = ajaxResult.data.password;
						this.editForm.tel = ajaxResult.data.tel;
						this.editForm.email = ajaxResult.data.email;
						this.editForm.state = ajaxResult.data.state;
					}else {
						this.message({
							message:"获取失败",
							type:'error'
						})
					}
				}).catch(error=>{
					this.$message({
						message:"获取失败",
						type:'success'
					})
				})
            },
            //显示新增界面
            handleAdd: function () {
                this.addFormVisible = true;
                this.addForm = {
                    name: '',
                    sn:''
                };
            },
            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            let para = Object.assign({}, this.editForm);
                            this.$http.post("/employee/update",para).then(res =>{
                                let ajaxResult = res.data
                                if (ajaxResult.success){
                                    this.$message({
                                        message:"修改成功",
                                        type:'success'
                                    })
                                    this.$refs['editForm'].resetFields();
									this.editLoading = false;
                                    this.editFormVisible = false;
                                    this.getListData();
                                }else {
									this.editLoading = false;
                                    this.message({
                                        message:"修改失败",
                                        type:'error'
                                    })

                                }
                            }).catch(error=>{
                                this.$message({
                                    message:"修改失败",
                                    type:'success'
                                })
                            })
                            /*para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                            editUser(para).then((res) => {
                                this.editLoading = false;
                                //NProgress.done();
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['editForm'].resetFields();
                                this.editFormVisible = false;
                                this.getListData();
                            });*/
                        });
                    }
                });
            },
            //新增
            addSubmit: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            //准备参数，将参数拷贝到para中
                            let para = Object.assign({}, this.addForm);
                            this.$http.post('/employee/add',para).then(res =>{
                                let ajaxResult = res.data
                                if (ajaxResult.success){
                                    this.$message.success("保存成功");
                                    this.addFormVisible = false;
                                    this.$refs['addForm'].resetFields();
                                    this.getListData();
                                }else {
                                    this.addFormVisible = false;
                                    this.$message({
                                        message: '保存失败',
                                        type: 'error'
                                    });
                                }
                                this.addLoading = false;
                            }).catch(error =>{
                                this.addLoading = false;
                                this.$message({
                                    message: '保存失败',
                                    type: 'error'
                                });
                            })
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id)
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = { ids: ids };
                    this.$http.post("/employee/batchDelete",para).then(res=>{
                        let ajaxResult = res.data;
                        if (ajaxResult.success){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getListData();
                        }else {
                            this.$message({
                                message: '删除失败',
                                type: 'error'
                            });
                        }
                        this.listLoading = false;
                    }).catch(error => {
                        this.listLoading = false;
                        this.$message({
                            message: '删除失败',
                            type: 'error'
                        });
                    })

                })
            },

			//分配角色
            async handleRole(index,row){
                this.userInfo=row;
                //在展示对话框之前获取，所有角色
				const {data:res} = await this.$http.get('/role/findRoleAll')
				if(!res.success){
				    this.$message.error('获取角色列表失败')
				}else {
					this.roleList=res.data;
				}
				this.RoleVisible=true;
			},

			//点击按钮保存分配角色
            async saveRoleInfo(){
				if(!this.selectRoleId){
				    return this.$message.error('请选择要分配的角色')
				}
                const {data:res} = await this.$http.post('/employee/updateEmployeeRoleById/'+this.userInfo.id+"/"+this.selectRoleId)
				if(!res.success){
				    this.$message.error('分配角色失败')
				}else {
				    this.$message.success('分配角色成功')
				}
                this.getListData();
				this.selectRoleId='',
                this.RoleVisible=false;
			}
        },
        mounted() {
            this.getListData();
        }
    }

</script>

<style scoped>

</style>